<template>
  <div class="container">
    <div class="app-container">
      <el-button type="primary" size="mini" class="btn-add" @click="dialogVisible = true">添加权限</el-button>
      <el-table :data="tableData" row-key="id" default-expand-all border>
        <el-table-column label="名称" prop="name"></el-table-column>
        <el-table-column label="标识" prop="code" ></el-table-column>
        <el-table-column label="描述" prop="description"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="text" v-if="row.type === 1" @click="childAdd(row.id)">添加</el-button>
            <el-button type="text" @click="edit(row.id)">编辑</el-button>
            <el-button type="text" @click="deleteRow(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加权限点的dialog弹层组件 -->
    <AddPermission :dialogVisible.sync="dialogVisible" @getPermissionList="getPermissionList" ref="add"/>
  </div>
</template>

<script>
  import { getPermissionList, getPermissionDetail, deletePermission } from '@/api/permission'
  import { transListToTreeData } from '@/utils'
  import AddPermission from './components/AddPermission'
  export default {
    name: 'Permission',
    components: { AddPermission },
    data() {
      return {
        // 添加弹层组件可见性
        dialogVisible: false,
        // 表格页面数据
        tableData: [],
      }
    },
    methods: {
      // 获取权限点列表
      async getPermissionList() {
        // 调用获取权限点列表的请求接口
        const result = await getPermissionList()
        this.tableData = transListToTreeData(result, 0)
      },
      // 点击表格行中的添加按钮，实现子节点的添加
      childAdd(id) {
        // 弹层可见
        this.dialogVisible = true
        // 修改权限点类型为按钮权限点
        this.$refs.add.form.type = 2
        // 给需要添加的子节点的pid赋值为父节点的id
        this.$refs.add.form.pid = id
      },
      // 修改对应权限点
      async edit(id) {
        // 弹层可见
        this.dialogVisible = true
        // 调用获取对应行权限详情的请求接口
        const result = await getPermissionDetail(id)
        this.$refs.add.form = result
      },
      // 删除表格行里的数据
      deleteRow(id) {
        this.$confirm('确定要删除该数据吗').then(async () => {
          // 调用删除权限点的请求接口
          await deletePermission(id)
          this.$message({ type: 'success', message: '删除成功!'})
          // 重新发送请求，获取权限点列表，重新渲染表格页面
          this.getPermissionList()
        }).catch(() => {})
      }
    },
    created() {
      this.getPermissionList()
    }
  }
</script>

<style scoped>
  .app-container {
    padding: 18px;
  }
  .btn-add {
    margin-bottom: 10px;
  }
  .el-table {
    font-size: 14px;
  }
</style>
